package com.sk.weichat.ui.message;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.qrcode.utils.UriUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sk.weichat.R;
import com.sk.weichat.bean.ChatBgBean;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.CameraUtil;
import com.sk.weichat.util.LiveDataBus;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.TipDialog;

import java.io.File;
import java.util.List;

/**
 * @author lzs
 * @date 2019/9/17
 * Email:343067508@qq.com
 **/
public class ChatBackgroundActivity extends BaseActivity implements PermissionUtil.OnRequestPermissionsResultCallbacks {

    public static final String event_change_chat_bg = "ChatBackgroundActivity_event_change_bg";

    private static final int request_select_bg = 7892;

    private String chatID = "";
    private final static int REQUEST_PICK_IMAGE = 7345;
    private final static int REQUEST_CAMERA_CODE = 7829;


    /**
     * @param context
     * @param chatID  群聊传roomid  单聊传friendid
     */
    public static void startChatBackgroundActivity(Context context, String chatID) {
        Intent intent = new Intent(context, ChatBackgroundActivity.class);
        intent.putExtra("chatID", chatID);
        context.startActivity(intent);
    }

    public static void startChatBackgroundActivityForResult(Activity context, String chatID,int requestCode) {
        Intent intent = new Intent(context, ChatBackgroundActivity.class);
        intent.putExtra("chatID", chatID);
        context.startActivityForResult(intent,requestCode);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_background);
        getSupportActionBar().hide();

        chatID = getIntent() != null && getIntent().hasExtra("chatID") ? getIntent().getStringExtra("chatID") : "";
        TextView title = findViewById(R.id.tv_title_center);
        title.setText(getString(R.string.set_background));

        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //拍照
        findViewById(R.id.tv_select_from_cemara).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isReadContacts = PermissionUtil.checkSelfPermissions(ChatBackgroundActivity.this, new String[]{Manifest.permission.CAMERA});
                if (isReadContacts) {
                    takePhoto();
                } else {
                    PermissionUtil.requestPermissions(ChatBackgroundActivity.this, 0x02, new String[]{Manifest.permission.CAMERA});
                }
            }
        });
        //相册
        findViewById(R.id.tv_select_from_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImage();
//
            }
        });
        //系统背景图
        findViewById(R.id.tv_select_bg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatBackgroundListActivity.startChatBackgroundListActivity(ChatBackgroundActivity.this, chatID, request_select_bg);
            }
        });
    }

    private void takePhoto() {
        PictureSelector.create(ChatBackgroundActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void getImage() {
        startActivityForResult(CameraUtil.getPickImageIntent(), REQUEST_PICK_IMAGE);


        //CameraUtil.pickImageSimple(this, REQUEST_PICK_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (request_select_bg == requestCode) {
                //Log.e("lzs", "request_select_bg  result");
                String path = data.getStringExtra(ChatBgBean.Parcelable_Key);
                LiveDataBus.get().with(event_change_chat_bg, String.class).postValue(path);
                setResult(Activity.RESULT_OK);
                ToastUtil.showToast(mContext, getString(R.string.tips_set_chat_bg_succcess));
                finish();
            }
            if (PictureConfig.CHOOSE_REQUEST == requestCode) {
                //Log.e("lzs", "CHOOSE_REQUEST  result");
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                LiveDataBus.get().with(event_change_chat_bg, String.class).postValue(selectList.get(0).getPath());
                setResult(Activity.RESULT_OK);
                ToastUtil.showToast(mContext, getString(R.string.tips_set_chat_bg_succcess));
                finish();
            }

            if (REQUEST_PICK_IMAGE == requestCode) {
                if (data != null) {
                    String realPathFromUri = UriUtils.getPicturePathFromUri(this, data.getData());
                    if (!TextUtils.isEmpty(realPathFromUri)) {
                        Log.e("lzs", "REQUEST_PICK_IMAGE  result");
                        LiveDataBus.get().with(event_change_chat_bg, String.class).postValue(realPathFromUri);
                        setResult(Activity.RESULT_OK);
                        ToastUtil.showToast(mContext, getString(R.string.tips_set_chat_bg_succcess));
                        finish();
                    }
                    //
                } else {
                    Toast.makeText(this, "图片损坏，请重新选择", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        takePhoto();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(this, perms.toArray(new String[perms.size()]));
        String tips = "";
        if (perms.get(0).endsWith("android.permission.RECORD_AUDIO")) {
            tips = getString(R.string.permission_microphone);
        } else if (perms.get(0).endsWith("android.permission.CAMERA")) {
            tips = getString(R.string.permission_photo);
        }
        if (onceAgain) {
            TipDialog mTipDialog = new TipDialog(this);
            mTipDialog.setmConfirmOnClickListener(getString(R.string.tip_reject_permission_place_holder, tips), new TipDialog.ConfirmOnClickListener() {
                @Override
                public void confirm() {
                    //拍照权限
                    PermissionUtil.startApplicationDetailsSettings(ChatBackgroundActivity.this, REQUEST_CAMERA_CODE);
                }
            });
            mTipDialog.show();
        } else {
            ToastUtil.showToast(ChatBackgroundActivity.this, getString(R.string.tip_permission_reboot_place_holder, tips));
        }
    }
}
